#include "kv_store.h"

// 初始化键值存储
KVStore *kv_store_init(const char *filename) {
    KVStore *store = (KVStore *)malloc(sizeof(KVStore));
    if (!store) {
        return NULL;
    }
    
    store->head = NULL;
    store->filename = strdup(filename);
    
    // 尝试从文件加载数据
    kv_store_load(store);
    
    return store;
}

// 关闭键值存储并释放资源
void kv_store_close(KVStore *store) {
    if (!store) {
        return;
    }
    
    // 保存数据到文件
    kv_store_save(store);
    
    // 释放链表内存
    Node *current = store->head;
    while (current) {
        Node *next = current->next;
        free(current);
        current = next;
    }
    
    free(store->filename);
    free(store);
}

// 存储键值对
bool kv_store_put(KVStore *store, const char *key, const char *value) {
    if (!store || !key || !value) {
        return false;
    }
    
    // 检查键长度
    if (strlen(key) >= MAX_KEY_SIZE || strlen(value) >= MAX_VALUE_SIZE) {
        return false;
    }
    
    // 查找是否已存在该键
    Node *current = store->head;
    while (current) {
        if (strcmp(current->key, key) == 0) {
            // 更新现有值
            strcpy(current->value, value);
            return true;
        }
        current = current->next;
    }
    
    // 创建新节点
    Node *new_node = (Node *)malloc(sizeof(Node));
    if (!new_node) {
        return false;
    }
    
    strcpy(new_node->key, key);
    strcpy(new_node->value, value);
    new_node->next = store->head;
    store->head = new_node;
    
    return true;
}

// 获取键对应的值
char *kv_store_get(KVStore *store, const char *key) {
    if (!store || !key) {
        return NULL;
    }
    
    Node *current = store->head;
    while (current) {
        if (strcmp(current->key, key) == 0) {
            // 返回值的副本
            char *value = (char *)malloc(strlen(current->value) + 1);
            if (value) {
                strcpy(value, current->value);
            }
            return value;
        }
        current = current->next;
    }
    
    return NULL; // 未找到键
}

// 删除键值对
bool kv_store_delete(KVStore *store, const char *key) {
    if (!store || !key) {
        return false;
    }
    
    // 特殊情况：删除头节点
    if (store->head && strcmp(store->head->key, key) == 0) {
        Node *temp = store->head;
        store->head = store->head->next;
        free(temp);
        return true;
    }
    
    // 查找并删除非头节点
    Node *current = store->head;
    while (current && current->next) {
        if (strcmp(current->next->key, key) == 0) {
            Node *temp = current->next;
            current->next = current->next->next;
            free(temp);
            return true;
        }
        current = current->next;
    }
    
    return false; // 未找到键
}

// 从文件加载键值对
bool kv_store_load(KVStore *store) {
    if (!store || !store->filename) {
        return false;
    }
    
    FILE *file = fopen(store->filename, "r");
    if (!file) {
        return false; // 文件不存在，无需加载
    }
    
    char key[MAX_KEY_SIZE];
    char value[MAX_VALUE_SIZE];
    
    // 清空现有数据
    Node *current = store->head;
    while (current) {
        Node *next = current->next;
        free(current);
        current = next;
    }
    store->head = NULL;
    
    // 逐行读取键值对
    char line[MAX_KEY_SIZE + MAX_VALUE_SIZE + 2];
    while (fgets(line, sizeof(line), file) != NULL) {
        // 简单的解析方法，先读取key，然后读取剩余部分作为value
        int i = 0;
        // 跳过前导空白
        while (line[i] && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n' || line[i] == '\r')) {
            i++;
        }
        // 读取key
        int key_start = i;
        while (line[i] && line[i] != ' ' && line[i] != '\t' && line[i] != '\n' && line[i] != '\r') {
            i++;
        }
        if (key_start == i) continue; // 空行或只有空白
        
        int key_len = i - key_start;
        if (key_len >= MAX_KEY_SIZE) key_len = MAX_KEY_SIZE - 1;
        strncpy(key, line + key_start, key_len);
        key[key_len] = '\0';
        
        // 跳过key后的空白
        while (line[i] && (line[i] == ' ' || line[i] == '\t')) {
            i++;
        }
        
        // 读取value（直到行尾）
        int value_start = i;
        while (line[i] && line[i] != '\n' && line[i] != '\r') {
            i++;
        }
        
        int value_len = i - value_start;
        if (value_len >= MAX_VALUE_SIZE) value_len = MAX_VALUE_SIZE - 1;
        strncpy(value, line + value_start, value_len);
        value[value_len] = '\0';
        
        kv_store_put(store, key, value);
    }
    
    fclose(file);
    return true;
}

// 将键值对保存到文件
bool kv_store_save(KVStore *store) {
    if (!store || !store->filename) {
        return false;
    }
    
    FILE *file = fopen(store->filename, "w");
    if (!file) {
        return false;
    }
    
    Node *current = store->head;
    while (current) {
        fprintf(file, "%s %s\n", current->key, current->value);
        current = current->next;
    }
    
    fclose(file);
    return true;
}